import type { deleteById } from "@/api/system/menu";
import { notify, confirm } from "@/utils/element";
import { ref, unref, reactive, toRefs, onMounted, onUnmounted, nextTick } from "vue";
import type { Ref } from "vue";

interface Params {
    disableMounted?: boolean|Ref; // 是否在mounted时执行查询
    mustQuery?: any;
    getPageList: Function;
    deleteById: Function;
}

// 分页列表页面通用逻辑
function useTablePage<T = any, Q = any>(params:Params, emit?:Function, props?:any) {
    // 列表ref
    const tableListRef = ref();
    // 修改弹窗ref
    const editRef = ref();
    // 定义屏幕高度
    const screenHeight = ref(window.innerHeight);
    // 声明状态
    const state = reactive({
        // 列表loading
        loading: false,
        // 列表查询参数
        query: {} as Q,
        // 列表分页
        page: {
            current: 1,
            size: 20,
            total: 0
        },
        // 列表数据
        tableList: [] as T[],
        // 表格高度
        tableHeight: 0,
    })

    onMounted(() => {
        // 监听窗口变化，动态计算表格高度
        window.addEventListener('resize', handleResize)
        // 页面首次加载，先调用一次
        handleResize()
        // 禁用首次加载，方便组件中其他位置触发加载
        if (unref(params.disableMounted)) return;
        queryData()
    })


    onUnmounted(() => {
        window.removeEventListener('resize', handleResize)
    })
    
    // 监听窗口变化，动态计算表格高度
    function handleResize() {
        screenHeight.value = window.innerHeight
        state.tableHeight = screenHeight.value - 245
    }

    // 分页条件查询列表数据
    async function queryData() {
        // 返回Promise方便后期扩展
        return new Promise(async (resolve, reject) => {
            // 开启loading
            state.loading = true;
            const query = params.mustQuery ?
                Object.assign({}, state.query, params.mustQuery) : state.query;
            params.getPageList && params.getPageList(query, state.page.current, state.page.size).then((res:any) => {
                state.loading = false;
                const { records, total } = res.data;
                // 列表数据先清空
                state.tableList = []
                nextTick(() => {
                    // 赋值列表数据
                    state.tableList = records;
                    // 赋值分页数据
                    state.page.total = total;
                })
                resolve(res)
            }).catch((err:Error) => {
                reject(err)
            }).finally(() => {
                // 关闭loading
                state.loading = false;
            })
        })
    }

    // 条件查询
    function handleQuery() {
        state.page.current = 1;
        queryData()
    }

    // 新增（调用时没有传递要加上小括号）
    function handleAdd(parentId?: string) {
        editRef.value.open('add', '新增', {parentId})
    }

    // 修改
    function handleEdit(row: T) {
        editRef.value.open('edit', '修改', row)
    }

    // 删除
    async function handleDelete(id: string) {
        try {
            state.loading = true
            if (params.deleteById) await params.deleteById(id)
            // 成功
            notify('删除成功', { type: 'success' })
            // 刷新列表
            handleQuery()
        } catch(error) {
            // ignore
        } finally {
            state.loading = false
        }
    }

    return {
        ...toRefs(state),
        tableListRef,
        editRef,
        queryData,
        handleQuery,
        handleAdd,
        handleEdit,
        handleDelete
    }
}

export { useTablePage }

export default useTablePage